import { SIGNUP } from '../actionTypes';
import fetch from '../utils/fetch';
import config from '../config';
import { message } from 'antd';

export const update = (payload) => ({
  type: SIGNUP,
  payload,
});

export const change = (key, value) => (dispatch) => {
  dispatch(update({
    [key]: value,
  }));
};

export const submit = (username, password) => async (dispatch, getState) => {
  const { username, id_number, phone, password, rePassword } = getState().signup;

  if (!username || !id_number || !phone || !password || !rePassword) {
    return false;
  }

  const res = await fetch({
    method: 'POST',
    url: `${config.host}/api/auth/signup`,
    param: {
      username, id_number, phone, password, rePassword,
    }
  }).catch(ex => console.error(ex));
  if (res.code === 200) {
    const { uid, token } = res.data;
    localStorage.setItem('token', token);
    message.success('注册成功', 3);
    setTimeout(() => {
      location.replace(`#/my?uid=${uid}`);
    }, 3000);
  } else {
    message.error(res.msg || '注册失败，请稍后重试');
  }
};
